package com.example.demo1122.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo1122.domain.ResponseResult;
import com.example.demo1122.entity.Class;
import com.example.demo1122.entity.Course;
import com.example.demo1122.entity.Teacher;
import com.example.demo1122.entity.Teacherforclass;
import com.example.demo1122.mapper.ClassMapper;
import com.example.demo1122.mapper.TeacherMapper;
import com.example.demo1122.mapper.TeacherforclassMapper;
import com.example.demo1122.service.ITeacherService;
import com.example.demo1122.service.ITeacherforclassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;

import java.util.List;

import static org.apache.logging.log4j.util.Strings.isEmpty;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author baomidou
 * @since 2023-12-08
 */
@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements ITeacherService {
    @Autowired
    private PasswordEncoder passwordEncoder;

    private final TeacherMapper teacherMapper;

    @Autowired
    private ClassMapper classMapper;
    @Autowired
    private TeacherforclassMapper teacherforclassMapper;
    @Autowired
    private ITeacherforclassService teacherforclassService;
    @Autowired
    public TeacherServiceImpl(TeacherMapper teacherMapper) {
        this.teacherMapper = teacherMapper;
    }
    @Autowired
    public CourseServiceImpl courseService;

    @Override
    public ResponseResult saveTeacher(Teacher teacher) {
        if(isEmpty(teacher.getTeacherID())){
            return new ResponseResult(713, "工号不能为空");
        }
        else{
            if (teacherMapper.isTeacherIDExists(teacher)) {
                // 教师ID已存在，报错
                if((getById(teacher.getTeacherID()).getName()).equals(teacher.getName())){
                    System.out.println("调用了已经存在");
                    return new ResponseResult(709, "该教师已存在");
                }
                else {
                    System.out.println("调用了ID已经被占用接口");
                    return new ResponseResult(708,teacher.getName()+"的ID已被占用");

                }
            } else {
                // 教师ID不存在，执行插入操作
                System.out.println("调用了插入");
                teacherMapper.insert(teacher);
                return new ResponseResult(710, "插入成功");
            }
        }
    }
//更新老师信息
    @Override
    public ResponseResult updateTeacher(Teacher teacher) {
        if(isEmpty(teacher.getTeacherID())){
            return new ResponseResult(713, "工号不能为空");
        }
        else{
            if (teacherMapper.isTeacherIDExists(teacher)) {
                // 教师ID已存在，执行更新操作
                teacherMapper.update(teacher);
                return new ResponseResult(715, "修改成功");
            } else {
                // 教师ID不存在，报错
                //teacherMapper.insert(teacher);
                return new ResponseResult(710, "修改失败,教工号不存在");
            }
        }
    }

    // 新增保存学生列表的方法
    public ResponseResult saveTeacherList(List<Teacher> teacherList) {

        try {
            List<String> occupiedNames = new ArrayList<>(); // 用于存储已被占用的姓名
            for (Teacher teacher : teacherList) {
                // 设置默认密码和身份信息

                teacher.setPassword(passwordEncoder.encode("123456"));

                // 尝试保存或更新信息
                ResponseResult result = saveTeacher(teacher);
                // 检查返回状态码，如果是208（即学生ID已被占用），则收集学生姓名
                if (result.getCode() == 708) {
                    occupiedNames.add(teacher.getName());
                }
            }
            if (!occupiedNames.isEmpty()) {
                // 返回包含所有占用姓名的消息
                return new ResponseResult(308, "以下教师的ID已被占用: " + String.join(", ", occupiedNames));
            } else {
                // 如果没有占用的学生姓名，表示批量插入/更新操作成功完成
                return new ResponseResult(300, "批量导入成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseResult<>(500, "批量插入失败", null);
        }
    }

    @Override
    public void findAll() {
        teacherMapper.findAll();

    }

    @Override
    public Page<Teacher> findPage(Page<Teacher> page, String teacherID, String name) {
        return teacherMapper.findPage(page, teacherID, name);
    }

    //********************************************************________________________________________________________________________________________________
    @Override
    public ResponseResult saveClass(Class class1) {

//        if (classMapper.isClassIDExists(class1)>0) {
//            // ID已存在，执行更新操作
//            classMapper.update(class1);
//            return new ResponseResult(305, "修改成功");
//        } else {
            // ID不存在，执行插入操作

            classMapper.insert(class1);
            return new ResponseResult(300, "插入成功");
       // }

    }

    @Override
    public ResponseResult updateClass(Class class1) {

        if (classMapper.isClassIDExists(class1.getClassID())>0) {
            // ID已存在，执行更新操作

            classMapper.update(class1);
            return new ResponseResult(305, "修改成功");
        } else {
        // ID不存在
        return new ResponseResult(400, "课堂不存在");
         }

    }
    public ResponseResult  findclassByTeacherId(String teacherID) {


            // 调用ClassStuMapper的方法来获取所有的studentID
            List<Class> classes = classMapper.selectclassByTeacherId(teacherID);
            if (classes.isEmpty()) {
                // 列表为空，返回空列表而不是null
                return new ResponseResult<>(HttpStatus.OK.value(), "该教师没有创建过课堂", Collections.emptyList());
            } else {
                // 对每个Class对象填充教师姓名和课程名称
                for (Class classItem : classes) {
                    // 根据teacherID获取到教师对象从而得到教师姓名
                    Teacher teacher = getById(classItem.getTeacherID());
                    if (teacher != null) {
                        classItem.setName(teacher.getName()); // 设置教师姓名
                    }

                    // 根据courseID获取到课程对象从而得到课程名称
                    Course course = courseService.getById(classItem.getCourseID());
                    if (course != null) {
                        classItem.setCourseName(course.getCourseName()); // 设置课程名称
                    }
                }
                // 存在，返回列表
                return new ResponseResult<>(HttpStatus.OK.value(), "查询成功", classes);
            }

    }

    @Override
    public Page<Class> findPageclass(Page<Class> page, Integer classID,String className,String teacherID,Integer courseID) {
        return classMapper.findPage(page, classID, className, teacherID, courseID);
    }
    //新增老师与课堂间的关系
    @Override
    public ResponseResult addTAToClass(String teacherID, String teacherName, Integer classID){

       String name=teacherMapper.selectById(teacherID).getName();
       if(!teacherName.equals(name)){
            return new ResponseResult(201, "教师姓名与ID不匹配");
        }
        int count = teacherforclassMapper.countByClassIdAndTeacherId(classID, teacherID);
        if (count == 0) {
            // 如果不存在，执行插入操作
            Teacherforclass teacherforclass = new Teacherforclass();
            teacherforclass.setTeacherID(teacherID);
            teacherforclass.setClassID(classID);
            teacherforclass.setTeacherName(teacherName);
            teacherforclassMapper.insert(teacherforclass);
        }
        return new ResponseResult(200, "成功添加助教");
    }

    //根据老师ID查看加入的课堂（创建的和管理的）
    @Transactional
    public ResponseResult findjoinclassByTeacherId(String teacherID) {
        // 首先检查ID是否存在
        if(!teacherIdExists(teacherID)){
            if (getById(teacherID)==null) {
                // ID不存在，返回相应提示
                return new ResponseResult<>(HttpStatus.NOT_FOUND.value(), "该teacherID不存在", Collections.emptyList());
            }
            return new ResponseResult<>(2241, "该教师未加入课堂", Collections.emptyList());
        }else {
            // 调用ClassStuMapper的方法来获取所有的classID
            List<String> classIds = teacherforclassMapper.selectClassIdsByTeacherID(teacherID);
            List<Class> classes=classMapper.selectBatchIds(classIds);
            if (classes.isEmpty()) {
                // 列表为空，返回空列表而不是null
                return new ResponseResult<>(HttpStatus.OK.value(), "没有课堂", Collections.emptyList());
            } else {
                // 存在，返回学生列表
                return new ResponseResult<>(HttpStatus.OK.value(), "查询成功", classes);
            }
        }
    }

    // 在StudentService.java
    public List<Teacher> findTeachersByClassId(Integer classID) {
        // 调用ClassStuMapper的方法来获取所有的studentID
        List<String> teacherIds = teacherforclassMapper.selectTeacherIdsByClassId(classID);
        if (teacherIds.isEmpty()) {
            // 返回空列表或适当的错误响应
        } else {
            // 执行查询
        }

        // 从student表中获取所有的学生信息
        return teacherMapper.selectBatchIds(teacherIds);
    }
    // 检查teacherID是否存在于教师-课堂表的方法
    private boolean teacherIdExists(String teacherID) {
        // 假设你有一个方法来检查classID是否存在于classstu表中
        // 返回true如果存在，false如果不存在

        return teacherforclassService.existsTeacherId(teacherID);
    }



}
